package kmp;

public class leetCode8_myAtoi {

    public static void main(String[] args) {
        leetCode8_myAtoi a = new leetCode8_myAtoi();
        a.myAtoi(" -42");
        System.out.println(1);
    }

    public int myAtoi(String s){

        if(s == null || s.length() == 0) return 0;

        int n = s.length();

        // str.charAt(i) 方法回去检查下标的合法性，一般先转换成字符数组
        char[] charArray = s.toCharArray();

        // 1、去除前导空格
        int index = 0;
        while (index < n && charArray[index] == ' '){
            index++;
        }
        if(index == n){
            return 0;
        }

        int sign = 1;
        if(charArray[index] == '-'){
            sign = -1;
            index++;
        }else if(charArray[index] == '+'){
            index++;
        }

        int res = 0;
        while (index < n){
            char cur = charArray[index];
            int x = cur - '0';
            if(cur > '9' || cur < '0'){
                break;
            }
            if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10) && x > 7) {
                if (sign > 0) {
                    return Integer.MAX_VALUE;
                }
                return Integer.MIN_VALUE;
            }
            res = res * 10 + x;
            index++;
        }
        return res * sign;
    }

    public int myAtoi2(String s){
        if(s == null || s.length() == 0) return 0;
        int result = 0;
        char[] chars = s.toCharArray();
        int n = chars.length;
        int index = 0;
        while (index < n && chars[index] == ' '){
            index++;
        }
        if(index == n){
            return 0;
        }
        int sign = 1;
        if(chars[index] == '-'){
            sign = -1;
            index++;
        }else if(chars[index] == '+'){
            index++;
        }
        while (index < n){
            if(chars[index] < '0' || chars[index] > '9'){
                break;
            }
            int a = chars[index] - '0';
            if(result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE/10 && a > 7)){
                if(sign > 0){
                    return Integer.MAX_VALUE;
                }else{
                    return Integer.MIN_VALUE;
                }
            }

            result = result * 10 + a;
            index++;
        }
        return result * sign;

    }
}
